//
//  IMKeychainUUIDManager.m
//  DualMediationSDK
//
//  Created by Assistant on 2024/01/01.
//  Copyright © 2024 IM. All rights reserved.
//

#import "IMKeychainUUIDManager.h"
#import <Security/Security.h>

static NSString *const kIMLoginUUIDKeychainKey = @"com.im.dualmediationsdk.login.uuid";
static NSString *const kIMKeychainService = @"com.im.dualmediationsdk";

@implementation IMKeychainUUIDManager

+ (NSString *)getOrCreateLoginUUID {
    // 先尝试从钥匙串获取
    NSString *existingUUID = [self getLoginUUIDFromKeychain];
    if (existingUUID && existingUUID.length > 0) {
        return existingUUID;
    }
    
    // 如果不存在，生成新的UUID并保存
    NSString *newUUID = [[NSUUID UUID] UUIDString];
    [self saveLoginUUIDToKeychain:newUUID];
    
    return newUUID;
}

+ (void)clearLoginUUID {
    NSDictionary *query = @{
        (__bridge NSString *)kSecClass: (__bridge NSString *)kSecClassGenericPassword,
        (__bridge NSString *)kSecAttrService: kIMKeychainService,
        (__bridge NSString *)kSecAttrAccount: kIMLoginUUIDKeychainKey
    };
    
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    
    if (status != errSecSuccess && status != errSecItemNotFound) {
        NSLog(@"[IMKeychainUUIDManager] 清除登录UUID失败: %d", (int)status);
    } else {
        NSLog(@"[IMKeychainUUIDManager] 登录UUID已清除");
    }
}

+ (BOOL)hasLoginUUID {
    NSString *uuid = [self getLoginUUIDFromKeychain];
    return uuid != nil && uuid.length > 0;
}

#pragma mark - Private Methods

+ (nullable NSString *)getLoginUUIDFromKeychain {
    NSDictionary *query = @{
        (__bridge NSString *)kSecClass: (__bridge NSString *)kSecClassGenericPassword,
        (__bridge NSString *)kSecAttrService: kIMKeychainService,
        (__bridge NSString *)kSecAttrAccount: kIMLoginUUIDKeychainKey,
        (__bridge NSString *)kSecReturnData: @YES,
        (__bridge NSString *)kSecMatchLimit: (__bridge NSString *)kSecMatchLimitOne
    };
    
    CFTypeRef result = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
    
    if (status == errSecItemNotFound) {
        // 钥匙串中没有找到UUID，这是正常情况（首次使用）
        NSLog(@"[IMKeychainUUIDManager] 钥匙串中未找到UUID（首次使用）");
        return nil;
    } else if (status != errSecSuccess) {
        // 其他错误
        NSLog(@"[IMKeychainUUIDManager] 从钥匙串获取UUID失败: %d", (int)status);
        return nil;
    }
    
    NSData *data = (__bridge_transfer NSData *)result;
    if (data) {
        NSString *uuid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"[IMKeychainUUIDManager] 从钥匙串获取UUID成功: %@", uuid);
        return uuid;
    }
    
    return nil;
}

+ (void)saveLoginUUIDToKeychain:(NSString *)uuid {
    NSData *uuidData = [uuid dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *query = @{
        (__bridge NSString *)kSecClass: (__bridge NSString *)kSecClassGenericPassword,
        (__bridge NSString *)kSecAttrService: kIMKeychainService,
        (__bridge NSString *)kSecAttrAccount: kIMLoginUUIDKeychainKey,
        (__bridge NSString *)kSecValueData: uuidData,
        (__bridge NSString *)kSecAttrAccessible: (__bridge NSString *)kSecAttrAccessibleWhenUnlockedThisDeviceOnly
    };
    
    // 先删除已存在的项
    NSDictionary *deleteQuery = @{
        (__bridge NSString *)kSecClass: (__bridge NSString *)kSecClassGenericPassword,
        (__bridge NSString *)kSecAttrService: kIMKeychainService,
        (__bridge NSString *)kSecAttrAccount: kIMLoginUUIDKeychainKey
    };
    SecItemDelete((__bridge CFDictionaryRef)deleteQuery);
    
    // 添加新项
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    
    if (status == errSecSuccess) {
        NSLog(@"[IMKeychainUUIDManager] UUID保存到钥匙串成功: %@", uuid);
    } else {
        NSLog(@"[IMKeychainUUIDManager] UUID保存到钥匙串失败: %d", (int)status);
    }
}

@end